package com.dayaokeji.rhythmschoolstudent.client.home.course;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.dayaokeji.coursetable.CourseTableView;
import com.dayaokeji.coursetable.bean.CourseModel;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseFragment;
import com.dayaokeji.rhythmschoolstudent.client.main.MainActivity;
import com.dayaokeji.rhythmschoolstudent.client.main.MainFragment;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseEvent;
import com.dayaokeji.rhythmschoolstudent.utils.CourseUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.Page;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.CourseApi;
import com.dayaokeji.server_api.domain.AddCourse;
import com.dayaokeji.server_api.domain.Course;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

/**
 * 课程
 */
public class CourseTableFragment extends BaseFragment{

    private static final String EXTRA_START_TIME = "start_time";
    private static final String EXTRA_END_TIME = "end_time";
    private static final String EXTRA_WEEKS = "weeks";

    @BindView(R.id.course_table_view)
    CourseTableView courseTableView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private static final CourseApi courseApi = ApiUtils.getApi(CourseApi.class);
    private Call<ServerResponse<Page<Course>>> cycleCourseCall;
    private Call<ServerResponse<Page<Course>>> tempporaryCourseCall;

    private final List<Course> courses = new ArrayList<>();

    private String startTime;
    private String endTime;

    public static CourseTableFragment newInstance(String startTime, String endTime) {

        Bundle args = new Bundle();
        args.putString(EXTRA_START_TIME, startTime);
        args.putString(EXTRA_END_TIME, endTime);
        CourseTableFragment fragment = new CourseTableFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        startTime = getArguments().getString(EXTRA_START_TIME);
        endTime = getArguments().getString(EXTRA_END_TIME);
        Date startDate = DateUtils.formatDate(startTime, DateUtils.FORMAT_DATE);
        Date endDate = DateUtils.formatDate(endTime, DateUtils.FORMAT_DATE);
        CourseTableView.setData(startDate,endDate);
        return inflater.inflate(R.layout.fragment_course_table,container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        init();
    }


    private void init() {
        courses.clear();
        setupView();
        setOnListener();
    }

    private void setupView() {
        setRefreshLayout();
    }

    private void setRefreshLayout() {
        if (refreshLayout != null) {
            refreshLayout.autoRefresh();
        }
    }

    private void setOnListener() {
        courseTableView.setItemCourseClickListener(new CourseTableView.ItemCourseClickListener() {
            @Override
            public void onClick(View view, CourseModel courseModel) {
                for (Course cours : courses) {
                    if (cours.getCourseDetailId() == courseModel.getId()) {
                        Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                        intent.putExtra(CourseDetailActivity.EXTRA_COURSE_ENTITY,cours);
                        startActivity(intent);
                    }
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                courses.clear();
                cycleCourseCall();
            }
        });
    }



    /**
     * 周期课程
     */
    private void cycleCourseCall() {
        cycleCourseCall = requestCourse(1);
        cycleCourseCall.enqueue(new ServerCallback<Page<Course>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<Course>> response) {
                temporaryCourseCall();
                if (success) {
                    List<Course> courseList = response.getBody().getList();
                    for (Course course : courseList) {
                        if (!courses.contains(course)) {
                            courses.add(course);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<Page<Course>>> call, Throwable t) {
                try {
                    addDisposable(Observable.timer(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            temporaryCourseCall();
                        }
                    }));

                }catch (Exception e) {
                    e.printStackTrace();
                }
                super.onFailure(call, t);
            }
        });
    }

    /**
     * 临时课程
     */
    private void temporaryCourseCall() {
        tempporaryCourseCall = requestCourse(2);
        tempporaryCourseCall.enqueue(new ServerCallback<Page<Course>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<Course>> response) {
                if (refreshLayout != null && refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh();
                }
                if (success) {
                    List<Course> courseList = response.getBody().getList();
                    for (Course course : courseList) {
                        if (!courses.contains(course)) {
                            courses.add(course);
                        }
                    }

                    if (getActivity() != null && !getActivity().isFinishing()) {
                        if (courseTableView != null) {
                            courseTableView.setWeekCourseViewData(CourseUtils.paserCourseData(courses,weeks()));
                        }
                    }
                }
            }
            @Override
            public void onFailure(Call<ServerResponse<Page<Course>>> call, Throwable t) {
                if (refreshLayout != null && refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh();
                }
                super.onFailure(call, t);
            }
        });
    }

    private List<String> weeks() {
        Date startDate = DateUtils.formatDate(startTime, DateUtils.FORMAT_DATE);
        Date endDate = DateUtils.formatDate(endTime, DateUtils.FORMAT_DATE);
        return DateUtils.getDates(startDate,endDate);
    }

    private Call<ServerResponse<Page<Course>>> requestCourse(int courseType) {
        return courseApi.list(
                UserUtils.getUserInfo() == null ? "" : UserUtils.getUserInfo().getId(),
                1,
//                DateUtils.getCurrentMonday(),
                startTime+" 00:00:00",
//                DateUtils.getCurrentSunday(),
                endTime+" 23:59:59",
                UserUtils.getUserInfo() == null ? 0 : UserUtils.getUserInfo().getUniversityId(),
                courseType,
                1,
                10000
        );
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(UpdateCourseEvent updateCourseEvent) {
        if (updateCourseEvent != null) {
            final Course course = updateCourseEvent.getCourse();
            for (Course cours : courses) {
                if (cours.equals(course)) {
                    cours.setSignStatus(course.getSignStatus());
                }
            }
        }
        courses.clear();
        cycleCourseCall();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroy() {
        if (cycleCourseCall != null) {
            cycleCourseCall.cancel();
        }
        if (tempporaryCourseCall != null) {
            tempporaryCourseCall.cancel();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
